package com.xln.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.xln.configuration.OssConfig;
import com.xln.util.DateUtil;
import com.xln.util.ResEnum;
import com.xln.util.FileUploadUtil;
import com.xln.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Slf4j
public class FileUploadController {
    
    @Value("${upload.path:uploads}")
    private String uploadPath;
    
    /**
     * 上传图片
     * @param file 文件
     * @param request 请求
     * @return 上传结果
     */
    @PostMapping("/image0")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error(ResEnum.FILE_NULL);
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error(ResEnum.FILE_FORMAT_ERROR);
            }
            
            // 检查文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error(ResEnum.FILE_SIZE_ERROR);
            }
            
            // 获取项目根路径
//            String rootPath = request.getSession().getServletContext().getRealPath("/");
            String propertyRootPath = System.getProperty("user.dir");
            String fullPath = propertyRootPath + "\\src\\main\\resources\\static\\uploads";
            log.info("上传路径: {}", fullPath);

//            String path = getClass().getClassLoader().getResource("static/uploads").getPath();
//            log.info("上传路径2: {}", path);
            // 上传文件
            String fileUrl = FileUploadUtil.uploadFile(file, fullPath);
            
            // 返回成功结果
            Map<String, String> data = new HashMap<>();
            data.put("url", fileUrl);
            
            log.info("图片上传成功: {}", fileUrl);
            log.info("图片返回路劲: {}", fileUrl);
            return Result.success(ResEnum.FILE_SUCCESS,fileUrl);
            
        } catch (IOException e) {
            log.error("图片上传失败", e);
            return Result.error(ResEnum.FILE_UPLOAD_ERROR);
        } catch (Exception e) {
            log.error("图片上传异常", e);
            return Result.error(ResEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    @PostMapping("/image")
    public Result<String> uploadImageOSS(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error(ResEnum.FILE_NULL);
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error(ResEnum.FILE_FORMAT_ERROR);
            }

            // 检查文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error(ResEnum.FILE_SIZE_ERROR);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null ?
                    originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
            String fileName = UUID.randomUUID().toString() + extension;
            log.info("上传文件名: {}", fileName);
            String filePath = DateUtil.getCurrentDateDir()+ "/" + fileName;

            // 构建 OSS 对象键
            String objectName = ossConfig.getObjectDir() + filePath;

            // 上传文件到 OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossConfig.getBucketName(),
                    objectName,
                    file.getInputStream()
            );
            ossClient.putObject(putObjectRequest);

            // 构建文件访问 URL
            String fileUrl = "https://" + ossConfig.getBucketName() + "." +
                    ossConfig.getEndpoint() + "/" + objectName;

            log.info("图片上传成功: {}", fileUrl);
            return Result.success(ResEnum.FILE_SUCCESS, fileUrl);

        } catch (IOException e) {
            log.error("图片上传失败", e);
            return Result.error(ResEnum.FILE_UPLOAD_ERROR);
        } catch (Exception e) {
            log.error("图片上传异常", e);
            return Result.error(ResEnum.FILE_UPLOAD_ERROR);
        }
    }
}
